#!/usr/bin/env python
# -*- coding: utf-8 -*-

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List, Optional
from app.core.database import get_db
from app.core.security import get_current_active_user
from app.models.user import User
from app.models.role import Role
from app.schemas.role import RoleCreate, RoleUpdate, RoleInDB

router = APIRouter()

@router.post("", response_model=RoleInDB, summary="创建角色")
async def create_role(
    role: RoleCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """创建新角色"""
    # 检查角色名是否已存在
    if db.query(Role).filter(Role.name == role.name).first():
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="角色名已存在"
        )
    
    db_role = Role(**role.model_dump())
    db.add(db_role)
    db.commit()
    db.refresh(db_role)
    return db_role

@router.get("", response_model=List[RoleInDB], summary="获取角色列表")
async def get_roles(
    skip: int = 0,
    limit: int = 10,
    name: Optional[str] = None,
    status: Optional[int] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取角色列表，支持分页和筛选"""
    query = db.query(Role)
    
    if name:
        query = query.filter(Role.name.like(f"%{name}%"))
    if status is not None:
        query = query.filter(Role.status == status)
        
    roles = query.offset(skip).limit(limit).all()
    
    # 添加用户数量信息
    for role in roles:
        role.user_count = len(role.users)
    
    return roles

@router.get("/{role_id}", response_model=RoleInDB, summary="获取角色详情")
async def get_role(
    role_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """根据ID获取角色详情"""
    role = db.query(Role).filter(Role.id == role_id).first()
    if not role:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="角色不存在"
        )
    
    # 添加用户数量信息
    role.user_count = len(role.users)
    
    return role

@router.put("/{role_id}", response_model=RoleInDB, summary="更新角色信息")
async def update_role(
    role_id: int,
    role: RoleUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """更新角色信息"""
    db_role = db.query(Role).filter(Role.id == role_id).first()
    if not db_role:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="角色不存在"
        )
    
    # 检查角色名是否已存在
    if role.name and role.name != db_role.name:
        if db.query(Role).filter(Role.name == role.name).first():
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="角色名已存在"
            )
    
    for field, value in role.model_dump(exclude_unset=True).items():
        setattr(db_role, field, value)
    
    db.commit()
    db.refresh(db_role)
    
    # 添加用户数量信息
    db_role.user_count = len(db_role.users)
    
    return db_role

@router.delete("/{role_id}", status_code=status.HTTP_204_NO_CONTENT, summary="删除角色")
async def delete_role(
    role_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """删除角色"""
    role = db.query(Role).filter(Role.id == role_id).first()
    if not role:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="角色不存在"
        )
    
    # 检查是否有用户在使用该角色
    if role.users:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="该角色下还有用户，无法删除"
        )
    
    db.delete(role)
    db.commit() 